//
//  API.swift
//  MyWeatherApp
//
//  Created by 李胜兵 on 2021/2/27.
//  Copyright © 2021 shanghai. All rights reserved.
//

import Alamofire
import SwiftyJSON

typealias APIFetchCompleteBlock<R: APIRequest> = (R.APIResourceType) -> Void
final class API {
    let host: String
    var authToken: String?
    var userId: String?
    
    init(host: String) {
        self.host = host
    }
    
    func fetch<R: APIRequest>(_ request: R, complete: (APIFetchCompleteBlock<R>)? = nil) {
        let header: HTTPHeaders = [:]
        Alamofire.request(host + request.path, method: request.method, parameters: request.parameters, headers: header).responseJSON { (response) in
            guard let jsonString = response.result.value else {
                complete?(R.APIResourceType(raw: "error"))
                return
            }
            
            let request = """
                url: "\(self.host + request.path)",
                method: "\(request.method)"
            """
            print("loadAPI: \(request)")
            
            let json = JSON(jsonString)
            complete?(R.APIResourceType(raw: json))
        }
    }
}

extension API {
    static func current() -> API? {
        let api = API(host: "https://www.metaweather.com")
        api.authToken = ""
        api.userId = ""
        return api
    }
}
